﻿function IndexControl($indexControl) {
	var $this = this;
	var $indexList = $("ul", $indexControl);
	var $navForward = $("a.index-scroll#forward", $indexControl);
	var $navBackward = $("a.index-scroll#backward", $indexControl);
	var focusedItem = 0, selectedItem = 0;
	var controlWidth = 0;

	function makeOffset(item) {
		var $item = $($("li", $indexList).get(item));

		return { left: -($item.position().left - 0.5 * $indexControl.width() + 0.5 * $item.width()) };
	};

	function onFocusComplete(item) {
		focusedItem = item;
		if (focusedItem == 0)
			$navBackward.hide();
		else
			$navBackward.show();
		if (focusedItem == $("li", $indexList).size() - 1)
			$navForward.hide();
		else
			$navForward.show();
	}

	function forceFocus(item) {
		$indexList.animate(makeOffset(item), { complete: function () { onFocusComplete(item); } });
	}

	function focus(item) {
		var $img = $("img", $("li", $indexList).get(item));

		if ($img.width() == 0)
			$img.load(function () { forceFocus(item);	});
		else
			forceFocus(item);
	}

	$navForward.click(function () {
		focus(Math.min(focusedItem + 5, $("li", $indexList).size() - 1));
	});

	$navBackward.click(function () {
		focus(Math.max(focusedItem - 5, 0));
	});

	$(window).resize(function () {
		if (controlWidth != $indexControl.width())
			$indexList.css(makeOffset(focusedItem));
	});


	this.selectionRequested = function (item, photo) {
	};


	this.select = function (item) {
		$($("li", $indexList).get(selectedItem)).removeClass("selected");
		$($("li", $indexList).get(item)).addClass("selected");
		selectedItem = item;
		focus(item);
	};


	this.load = function (photos) {
		$indexList.empty();
		$.each(photos, function (i, item) {
			var $frame = $("<li><img src='" + item.thumbnail.src + "' alt=''/></li>");

			$indexList.append($frame);
			$frame.click(function () {
				$this.selectionRequested(i, item);
			});
		});
	};

	this.show = function (show) {
		$indexControl.animate({ bottom: show ? 0 : -$indexControl.height() });
	};
}
